#include <head.h>

int int_val = 50;
pthread_mutex_t mutex;

void *fun1(void *arg);
void *fun2(void *arg);

int main(int argc, char const *argv[])
{
    pthread_t tid1, tid2;
    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);
    // 创建两个线程
    pthread_create(&tid1, NULL, fun1, NULL);
    pthread_create(&tid2, NULL, fun2, NULL);
    // 等待线程结束
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);
    return 0;
}

void *fun1(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        printf("fun1:\n");
        int_val = int_val - 2;
        sleep(2);
        printf("线程1 int_val = %d\n", int_val);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

void *fun2(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        printf("fun2:\n");
        int_val = int_val - 4;
        sleep(2);
        printf("线程2 int_val = %d\n", int_val);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

